﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using GameSchool.Models;

            //var viewmodel = new TeacherPartialViewModel();
            //var teacherLogin = repository.GetTeacherLoginRelationship();



            //return View(viewmodel);

namespace GameSchool.Controllers
{
    public class StudentController : Controller
    {
        private IGameSchoolRepository repository = null;

        public StudentController()
        {
            repository = new GameSchoolRepository();
        }

        public StudentController(IGameSchoolRepository rep)
        {
            repository = rep;
        }
        //
        // GET: /Student/
        #region Views

        public ActionResult StudentHome()
        {
            var viewmodel = new StudentHomeViewModel();
            var studentLogin = repository.GetStudentLoginRelationship();

            List<StudentHomeViewModel.deadlinesListItem> dlListItem = new List<StudentHomeViewModel.deadlinesListItem>();

            // the following lines are all about finding the assignments or exams with upcoming deadlines and pushing them to the viewmodel.
            //find 3 assignments with the smallest deadline date
            var smallestAssigments = (from a in repository.getAssignments()
                                      orderby a.timeLimit ascending
                                      select a).Take(3);

            // find 3 exams with the smallest deadline date
            var smallestExams = (from x in repository.GetExams()
                                 orderby x.timeLimit ascending
                                 select x).Take(3);

            //here we make a combined list of smallestAssignments and smallestExams
            var numItemsInSmallestAssignments = smallestAssigments.Count();
            var numItemsInSmallestExams = smallestExams.Count();
            for (int i = 0; i < 2; i++)
            {
                if (numItemsInSmallestAssignments > 0) // if there is anything inside smallestAssignments
                {
                    dlListItem.Add(new StudentHomeViewModel.deadlinesListItem // add a new list item to dlList
                    {
                        courseName = smallestAssigments.ElementAt(i).title,
                        taskType = "Assignment",
                        level = smallestAssigments.ElementAt(i).level.ToString(),
                        daysLeft = smallestAssigments.ElementAt(i).timeLimit
                    });
                    numItemsInSmallestAssignments--;
                }
                if (numItemsInSmallestExams > 0) // if there is anything inside smallestExams
                {
                    dlListItem.Add(new StudentHomeViewModel.deadlinesListItem // add a new list item to dlList
                    {
                        courseName = smallestAssigments.ElementAt(i).title,
                        taskType = "Exam",
                        level = smallestAssigments.ElementAt(i).level.ToString(),
                        daysLeft = smallestAssigments.ElementAt(i).timeLimit
                    });
                    numItemsInSmallestExams--;
                }
            }

            // take the three smallest items from dlList
            var mostImmediateTasks = (from x in dlListItem
                                      orderby x.daysLeft ascending
                                      select x).Take(3);

            viewmodel.deadlines = mostImmediateTasks.ToList(); //...and finally, push mostImmediate tasks into the viewmodel.
            var allAchievements = repository.GetAchievements().ToList();
            viewmodel.listAchievements = allAchievements; //TODO: filter out the achievements by student
            viewmodel.studentName = studentLogin.name; //For the top bar
            viewmodel.sidebarCourses = repository.GetCoursesByStudent(studentLogin).ToList();
            viewmodel.listCourses = repository.GetCoursesByStudent(studentLogin).ToList();

            GameSchoolContext db = new GameSchoolContext();

            viewmodel.studentProgressDashboard = new List<StudentHomeViewModel.courseProgressOverview>();

            foreach (var item in viewmodel.listCourses)
            {
                viewmodel.studentProgressDashboard.Add(new StudentHomeViewModel.courseProgressOverview
                {
                    courseName = item.title,
                    currentLevelInCourse = repository.GetUnlockedLevelsByStudentAndCourse(studentLogin, item).Count(),
                    totalLevelsInCourse = repository.GetAllLevelsByCourse(item).Count(),
                    xpAboveStudent = repository.getXPofStudentAbove(item.courseID, studentLogin.studentID),
                    currentXPInCourse = (from l in db.studentCourses
                                         where item.courseID == l.courseID && studentLogin.studentID == l.studentID                                         
                                         select l.studentXP).SingleOrDefault(),                                         
                    xpBelowStudent = repository.getXPofStudentBelow(item.courseID, studentLogin.studentID)
                });
            }
            return View(viewmodel);
        }

        public ActionResult StudentCourseDashboard(string ID)
        {
            int courseID = Convert.ToInt32(ID);
            var viewmodel = new StudentDashboardViewModel();
            var studentLogin = repository.GetStudentLoginRelationship();
            var theCourse = repository.GetCourseByID(courseID);

            var smallestAssignmentsInCourse = (from a in repository.getAssignments()
                                               where a.levelID == courseID
                                               orderby a.timeLimit ascending
                                               select a).Take(3);

            var smallestExamsInCourse = (from x in repository.GetExams()
                                         where x.levelID == courseID
                                         orderby x.timeLimit ascending
                                         select x).Take(3);


            var numItemsInSmallestAssignments = smallestAssignmentsInCourse.Count();
            var numItemsInSmallestExams = smallestExamsInCourse.Count();
            List<StudentDashboardViewModel.deadlinesListItem> dlListItem = new List<StudentDashboardViewModel.deadlinesListItem>();
            for (int i = 0; i < 2; i++)
            {
                if (numItemsInSmallestAssignments > 0)
                {
                    dlListItem.Add(new StudentHomeViewModel.deadlinesListItem
                    {
                        courseName = smallestAssignmentsInCourse.ElementAt(i).title,
                        taskType = "Exam",
                        level = smallestAssignmentsInCourse.ElementAt(i).level.ToString(),
                        daysLeft = smallestAssignmentsInCourse.ElementAt(i).timeLimit
                    });
                    numItemsInSmallestAssignments--;
                }
                if (numItemsInSmallestExams > 0)
                {
                    dlListItem.Add(new StudentDashboardViewModel.deadlinesListItem
                    {
                        courseName = smallestExamsInCourse.ElementAt(i).title,
                        taskType = "Exam",
                        level = smallestExamsInCourse.ElementAt(i).level.ToString(),
                        daysLeft = smallestExamsInCourse.ElementAt(i).timeLimit
                    });
                    numItemsInSmallestExams--;
                }
            }
            viewmodel.deadlines = (from x in dlListItem
                                       orderby x.daysLeft ascending
                                       select x).Take(3).ToList();

            viewmodel.listAchievements = repository.GetAchievements().ToList();
            GameSchoolContext db = new GameSchoolContext();

            viewmodel.progressOverview = new StudentHomeViewModel.courseProgressOverview 
            {
                courseName = repository.GetCourseByID(courseID).title,
                currentLevelInCourse = repository.GetUnlockedLevelsByStudentAndCourse(studentLogin, repository.GetCourseByID(courseID)).Count(),
                totalLevelsInCourse = repository.GetAllLevelsByCourse(repository.GetCourseByID(courseID)).Count(),
                xpAboveStudent = repository.getXPofStudentAbove(courseID, studentLogin.studentID),
                currentXPInCourse = (from l in db.studentCourses
                                     where courseID == l.courseID && studentLogin.studentID == l.studentID
                                     select l.studentXP).SingleOrDefault(),
                xpBelowStudent = repository.getXPofStudentBelow(courseID, studentLogin.studentID)
            };

            viewmodel.sidebarCourses = repository.GetCoursesByStudent(studentLogin).ToList(); //for sidebar.
            viewmodel.courseName = repository.GetCourseByID(courseID).title;
            viewmodel.studentName = studentLogin.name; //for titlebar.
            viewmodel.listCourses = repository.GetCoursesByStudent(studentLogin).ToList();
            viewmodel.courseID = theCourse.courseID;
            return View(viewmodel);
        }


        public ActionResult Grades()
        {
            return View();
        }

        //For supervisor
        public ActionResult CreateStudent()
        {
            /*var course = repository.GetCourses().ElementAt(0);       <-.... who did that? Ólöf
            var test = repository.GetAllLevelsByCourse(course);
			return View(test);*/
			return View();
        }

        //For supervisor
		[HttpPost]
		public ActionResult CreateStudent(FormCollection formData) 
		{
			Student s = new Student();

			s.name = formData["name"];
			s.kennitala = Convert.ToInt32(formData["kennitala"]);
			s.address = formData["address"];
			s.zip = Convert.ToInt32(formData["zip"]);
			s.phone = Convert.ToInt32(formData["phone"]);
			s.email = formData["email"];			
			
			repository.AddStudent(s);
			repository.Save();

			return Redirect("~/Supervisor/SupervisorHome");
		}

        //For supervisor
        public ActionResult StudentEdit(int id)
        {
            // TODO if we have time - Ólöf
			return View();
        }

        //For supervisor
        [HttpPost]
        public ActionResult StudentEdit(int id, FormCollection formData)
        {
			// TODO if we have time - Ólöf
			return View();
        }

        #endregion

        public Notification GetNotifications(Notification theNotification)
        {
            return theNotification;
        }
    }
}
